# -*- coding:utf-8 -*-

from decimal import Decimal,getcontext,ROUND_HALF_DOWN
import time
from datetime import datetime
import tushare as ts
from dtrader.price_handler import AbstractTickPriceHandler
from dtrader import logger
from dtrader.dataseries.tick import BasicTick
from dtrader.dataseries.tickds import TickDataSeries
from dtrader.event import TickEvent,EventType
try:
    import Queue as queue
except ImportError:
    import queue


class TushareTestTickPriceHandler(AbstractTickPriceHandler):

    def __init__(self, events_queue, init_tickers,test_date = '2014-01-09'):

        self.__logger = logger.getLogger("TUSHARE_TEST_PRICE_HANDLER")
        self.events_queue = events_queue
        self.test_date = test_date
        self.tickers_data = {}
        # 订阅行情，并初始化行情数据
        if init_tickers is not None:
            self.subscribe_tickers(init_tickers)

    def subscribe_tickers(self,tickers=[]):

        """订阅行情，并初始化行情数据"""
        if isinstance(tickers, str):
            tickers = [tickers]

        for ticker in tickers:
            if ticker not in self.tickers_data.keys():
                df = ts.get_tick_data(ticker,date=self.test_date)
                fist_data = df.tail(1)
                tick = BasicTick(fist_data['time'].values[-1], fist_data['price'].values[-1], fist_data['price'].values[-1],
                                 fist_data['volume'].values[-1], fist_data['volume'].values[-1])
                ds = TickDataSeries()
                ds.append(tick)
                self.tickers_data[ticker] = ds

    def get_best_bid_ask(self,ticker):
        if not self.tickers_data.has_key(ticker):
            raise Exception("no ticker data of %s"%(ticker))
        lastTick = self.tickers_data[ticker][-1]
        if lastTick is not None and isinstance(lastTick,BasicTick):
            return lastTick.get_ask(),lastTick.get_bid()

    def fetch_tick_loop(self):
        """循环获取tick行情"""

        while 1:
            tickers = self.tickers_data.keys()
            print("test")
            for ticker in tickers:
                df = ts.get_tick_data(ticker, date=self.test_date)
                print(df)
                df = df.sort('time')
                for index, row in df.iterrows():
                    try:
                        tick = BasicTick(row['time'], Decimal(str(row['price'])),
                                         Decimal(str(row['price'])),
                                         Decimal(str(row['volume'])),
                                         Decimal(str(row['volume']))
                                         )
                        self.tickers_data[ticker].append(tick)
                        # push event to the queue
                        date_time  = datetime.strptime("%s %s"%(self.test_date, row['time']),"%Y-%m-%d %H:%M:%S")

                        tev = TickEvent(ticker, date_time, Decimal(str(row['price'])), Decimal(str(row['price'])), Decimal(str(row['volume'])), Decimal(str(row['volume'])))
                        print("%s"%(tev))
                        self.events_queue.put(tev)
                    except Exception,e:
                        print(e)
                    time.sleep(1)


